package com.lq.rabbitmq.deom08;

import com.lq.rabbitmq.utile.RabbitmqUtile;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *  死信队列
 *   消费者
 */
public class CouSummer01 {
    private static final String CHANGE_NAME="change_name";
    private static final String DEAD_NAME="dead_name";
    private static final String QUEUE_NAME="queue_name";
    private static final String QUEUE_DEAD="dead_name";

    public static void main(String[] args) throws IOException {
        Channel channel = RabbitmqUtile.createConnection();
         //声明交换机
        channel.exchangeDeclare(CHANGE_NAME, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_NAME, BuiltinExchangeType.DIRECT);
        //声明队列
        Map<String,Object>map =new HashMap<>();
        //添加过期时间   ms 单位
       // map.put("x-message-ttl",10*1000);
        //设置信息的长度限制
       // map.put("x-max-length",6);
        //设置死信交换机
        map.put("x-dead-letter-exchange",DEAD_NAME);
        //设置死信RoutingKey
        map.put("x-dead-letter-routing-key","lisi");
        channel.queueDeclare(QUEUE_NAME,false,false,false,map);

        channel.queueDeclare(QUEUE_DEAD,false,false,false,null);
      //绑定
         channel.queueBind(QUEUE_NAME,CHANGE_NAME,"zhangsan");
         channel.queueBind(QUEUE_DEAD,DEAD_NAME,"lisi");
        System.out.println("等待信息接收....");

        DeliverCallback deliverCallback=(Tag,message)->{
            String msg = new String(message.getBody(), "utf-8");
             if(msg.equals("info5")){
                 System.out.println("信息被拒绝:"+msg);
                 channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
             }else{
                 System.out.println("接收信息:"+msg);
                 channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
             }
        };
        //开启手动应答
        channel.basicConsume(QUEUE_NAME,false,deliverCallback,(counser)->{});
    }
}
